<?php

namespace app\admin\controller\shop;

use app\admin\model\goods\GoodsCategoryModel;
use app\admin\model\goods\GoodsModel;
use app\admin\model\shop\ShopGoodsCategoryModel;
use app\admin\model\shop\ShopGoodsModel;
use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 店铺
 *
 * @icon fa fa-circle-o
 */
class Shop extends Backend
{

    /**
     * ShopModel模型对象
     * @var \app\admin\model\shop\ShopModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\ShopModel;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list as &$value){
            $value['category_count'] = ShopGoodsCategoryModel::where('shop_id',$value['id'])->count();
            $value['goods_count'] = ShopGoodsModel::where('shop_id',$value['id'])->count();
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }


        if (strlen($params['password']) < 4 || strlen($params['password']) > 32) {
            $this->error(__('The password length can only be between 4 and 32 characters'));
        }

        $params['salt'] = Random::alnum();
        $params['password'] = $this->getEncryptPassword($params['password'], $params['salt']);

        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if (!empty($params['password'])) {
            if (strlen($params['password']) < 4 || strlen($params['password']) > 32) {
                $this->error(__('The password length can only be between 4 and 32 characters'));
            }

            $params['salt'] = Random::alnum();
            $params['password'] = $this->getEncryptPassword($params['password'], $params['salt']);
        }

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt 密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    /**
     * Notes: 门店分类管理
     * User: AerYYY
     * Date: 6/8/25
     * @return string|\think\response\Json
     * @throws DbException
     * @throws \think\Exception
     */
    public function class_manage($ids = null)
    {
        $this->model = new GoodsCategoryModel();

        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {

            $this->assignconfig('shop_id', $ids);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        $shop_id = input('shop_id');
        $shopGoodsCategoryModel = new ShopGoodsCategoryModel();
        $shopCategoryIds = $shopGoodsCategoryModel->where('shop_id', $shop_id)
            ->column('goods_category_id');


        $o_where = [];
        $filter = json_decode($this->request->get("filter"), true);
        $op = json_decode($this->request->get("op"), true);
        if (!empty($filter['have'])) {
            if ($filter['have'] == 100) {
                $o_where['id'] = ['not in', $shopCategoryIds];
            } else if ($filter['have'] == 200) {
                $o_where['id'] = ['in', $shopCategoryIds];
            }

            unset($filter['have'], $op['have']);
        }
        $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where($o_where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list->items() as &$item) {
            if (in_array($item['id'], $shopCategoryIds)) {
                $item['have'] = 200;
            } else {
                $item['have'] = 100;
            }
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * Notes: 添加门店分类
     * User: AerYYY
     * Date: 6/8/25
     * @return \think\response\Json
     */
    public function update_shop_category()
    {
        $ids = input('ids/a');
        $shop_id = input('shop_id');
        if (empty($ids)) {
            return json(['code' => 0, 'msg' => __('Please select the category.')]);
        }
        if (empty($shop_id)) {
            return json(['code' => 0, 'msg' => __('Shop id error')]);
        }

        $shopGoodsCategoryModel = new ShopGoodsCategoryModel();
        $old_category_ids = $shopGoodsCategoryModel->where('shop_id', $shop_id)->column('goods_category_id');

        $new_category_ids = array_diff($ids, $old_category_ids);

        if (empty($new_category_ids) || count($new_category_ids) <= 0) {
            return json(['code' => 0, 'msg' => 'success']);
        }

        $data = [];
        foreach ($new_category_ids as $v) {
            $data[] = [
                'shop_id' => $shop_id,
                'goods_category_id' => $v,
            ];
        }

        $shopGoodsCategoryModel->insertAll($data);

        return json(['code' => 0, 'msg' => 'success']);
    }


    /**
     * Notes: 删除门店分类
     * User: AerYYY
     * Date: 6/8/25
     * @return \think\response\Json
     */
    public function delete_shop_category()
    {
        $ids = input('ids/a');
        $shop_id = input('shop_id');
        if (empty($ids)) {
            return json(['code' => 0, 'msg' => __('Please select the category.')]);
        }
        if (empty($shop_id)) {
            return json(['code' => 0, 'msg' => __('Shop id error')]);
        }

        $shopGoodsCategoryModel = new ShopGoodsCategoryModel();
        $shopGoodsCategoryModel->whereIn('goods_category_id', $ids)->where('shop_id', $shop_id)
            ->delete();

        return json(['code' => 0, 'msg' => 'success']);
    }

    /**
     * Notes: 商品管理
     * User: AerYYY
     * Date: 6/8/25
     * @param $ids
     * @return string|\think\response\Json
     * @throws DbException
     * @throws \think\Exception
     */
    public function goods_manage($ids = null)
    {

        $this->model = new GoodsModel();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assignconfig('shop_id', $ids);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }


        $shop_id = input('shop_id');
        $shopGoodsModel = new ShopGoodsModel();
        $shopGoodsIds = $shopGoodsModel->where('shop_id', $shop_id)
            ->column('goods_id');


        $o_where = [];
        $filter = json_decode($this->request->get("filter"), true);
        $op = json_decode($this->request->get("op"), true);
        if (!empty($filter['have'])) {
            if ($filter['have'] == 100) {
                $o_where['id'] = ['not in', $shopGoodsIds];
            } else if ($filter['have'] == 200) {
                $o_where['id'] = ['in', $shopGoodsIds];
            }

            unset($filter['have'], $op['have']);
        }
        $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)->where($o_where)
            ->order($sort, $order)
            ->paginate($limit);

        foreach ($list->items() as &$item) {
            $item['category_name'] = GoodsCategoryModel::where('id', $item['category_id'])->value('name');
            if (in_array($item['id'], $shopGoodsIds)) {
                $item['have'] = 200;
            } else {
                $item['have'] = 100;
            }
        }

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * Notes: 添加门店商品
     * User: AerYYY
     * Date: 6/8/25
     * @return \think\response\Json
     */
    public function add_shop_goods()
    {
        $ids = input('ids/a');
        $shop_id = input('shop_id');
        if (empty($ids)) {
            return json(['code' => 1, 'msg' => __('Please select the category.')]);
        }
        if (empty($shop_id)) {
            return json(['code' => 1, 'msg' => __('Shop id error')]);
        }

        $shopGoodsModel = new ShopGoodsModel();
        $res = $shopGoodsModel->add_shop_goods($ids, $shop_id);

        if ($res === false) {
            return json(['code' => 1, 'msg' => __($shopGoodsModel->getError())]);
        }

        return json(['code' => 0, 'msg' => 'success']);
    }


    /**
     * Notes: 删除门店商品
     * User: AerYYY
     * Date: 6/8/25
     * @return \think\response\Json
     */
    public function delete_shop_goods()
    {
        $ids = input('ids/a');
        $shop_id = input('shop_id');
        if (empty($ids)) {
            return json(['code' => 1, 'msg' => __('Please select the category.')]);
        }
        if (empty($shop_id)) {
            return json(['code' => 1, 'msg' => __('Shop id error')]);
        }

        $shopGoodsModel = new ShopGoodsModel();
        $res = $shopGoodsModel->delete_shop_goods($ids, $shop_id);

        if ($res === false) {
            return json(['code' => 1, 'msg' => __($shopGoodsModel->getError())]);
        }

        return json(['code' => 0, 'msg' => 'success']);
    }


}
